export function basePromise<T = unknown>(
  cb: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: unknown) => void) => void
): Promise<T> {
  return new Promise((resolve, reject) => {
    cb(resolve, reject);
  });
}

export function getUserProfile(options: UniApp.GetUserProfileOptions): Promise<UniApp.GetUserProfileRes> {
  return basePromise<UniApp.GetUserProfileRes>((resolve, reject) => {
    // #ifdef MP-WEIXIN
    uni.getUserProfile({
      ...options,
      desc: options.desc || '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success(res) {
        console.log(res);

        if (res.errMsg === 'getUserProfile:ok') {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail(err) {
        reject(err);
      }
    });
    // #endif
    // #ifndef MP-WEIXIN
    // 修复非小程序平台不存在获取用户信息的api问题
    const userInfo: UniApp.GetUserProfileRes = {
      userInfo: {
        nickName: '随机姓名',
        openId: '777777',
        avatarUrl: ''
      },
      rawData: '',
      signature: '',
      encryptedData: '',
      iv: '',
      errMsg: ''
    };
    resolve(userInfo);
    // #endif
  });
}

export function login() {
  return basePromise((resolve, reject) => {
    uni.login({
      //获取code
      success(res) {
        if (res.errMsg === 'login:ok') {
          resolve(res.code);
        } else {
          reject(false);
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
}

/**
 * 获取图片信息api的promise化
 * @param options
 * @returns
 */
export function getImageInfo(src: string) {
  return basePromise<UniApp.GetImageInfoSuccessData>((resolve, reject) => {
    uni.getImageInfo({
      src,
      success(res) {
        resolve(res);
      },
      fail(err) {
        reject(err);
      }
    });
  });
}
